﻿IF EXISTS
(
    SELECT TOP (1)
           1
    FROM sysobjects
    WHERE id = OBJECT_ID(N'tr_FW_User_All')
          AND OBJECTPROPERTY(OBJECT_ID('tr_FW_User_All'), N'IsTrigger') = 1
)
BEGIN
    DROP TRIGGER tr_FW_User_All;
END;
GO

CREATE TRIGGER tr_FW_User_All
ON dbo.FW_User
AFTER UPDATE, DELETE, INSERT
AS
BEGIN
    DECLARE @IsInsert BIT,
            @IsUpdate BIT,
            @IsDelete BIT;
    IF EXISTS (SELECT 1 FROM inserted) AND NOT EXISTS (SELECT 1 FROM deleted)
        SET @IsInsert = 1;
    ELSE
        SET @IsInsert = 0;

    IF EXISTS (SELECT 1 FROM inserted) AND EXISTS (SELECT 1 FROM deleted)
        SET @IsUpdate = 1;
    ELSE
        SET @IsUpdate = 0;

    IF NOT EXISTS (SELECT 1 FROM inserted) AND EXISTS (SELECT 1 FROM deleted)
        SET @IsDelete = 1;
    ELSE
        SET @IsDelete = 0;

    DECLARE @UserIntID AS BIGINT;
    IF (@IsUpdate = 1)
    BEGIN

        -- 更改了用户名或者sign或者头像同步更新lay的表中
        UPDATE dbo.layim_user
        SET name = ins.UserName,
            [sign] = ins.UserSign,
            [avatar] = ISNULL(ins.UserImageUrl,'/images/photo/xiaopanzi.jpg')
        FROM dbo.layim_user lu
            INNER JOIN Inserted ins
                ON lu.id = ins.UserIntID;
    END;
    IF (@IsInsert = 1)
    BEGIN
        -- 新增
        SELECT @UserIntID = Inserted.UserIntID
        FROM Inserted;
        EXEC usp_FW_SyncLayIM @UserIntID = @UserIntID;
    END;
    IF (@IsDelete = 1)
    BEGIN
        -- 删除
        SELECT @UserIntID = Deleted.UserIntID
        FROM Deleted;
        DELETE FROM dbo.layim_user
        WHERE id = @UserIntID;
    END;

END;
